package xhwl.insurance.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.MyApp;
import xhwl.insurance.R;
import xhwl.insurance.event.LoginEvent;
import xhwl.insurance.upgrade.UpgradeEvent;
import xhwl.insurance.upgrade.UpgradeMgr;
import xhwl.insurance.util.AppUtil;
import xhwl.insurance.util.BaiduLocateMgr;
import xhwl.insurance.util.NumberJudgeUtils;
import xhwl.insurance.util.PermisionUtils;

/**
 * Created by admin on 2017-07-14.
 */

public class LoginActivityV2 extends BaseActivity implements View.OnClickListener {
    public static final String TAG = LoginActivityV2.class.getSimpleName();
    private EditText etPhone;
    private Button btnAuthCode;
    private TextView tvRule;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_login_v2);
    }

    @Override
    protected void processOper() {
        requestPermission();

    }



    private void initRuleText() {
        SpannableString jkcn = new SpannableString("《会员协议》");
        jkcn.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                // TODO Auto-generated method stub
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.login_text_color));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                // TODO Auto-generated method stub
//                ToastUtil.showToast(mContext,"onclick");
                String url = "http://wx-heartorg.yk2020.com/weixin/Application/Member/View/app/info.html";
                AppUtil.startWebViewActivity(mContext, url, "会员协议");
            }
        }, 0, jkcn.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvRule.setHighlightColor(Color.TRANSPARENT);
        tvRule.append("登录即代表阅读并同意");
        tvRule.append(jkcn);
        // tvRule.append(jkcn);
        tvRule.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    public void initViews() {
        initTitleViews();
        this.btnAuthCode = (Button) findViewById(R.id.btnAuthCode);
        this.etPhone = (EditText) findViewById(R.id.etPhone);
        this.tvRule = (TextView) findViewById(R.id.tvRule);
        initRuleText();
        String phone = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.LINK_MOBILE, "");
        etPhone.setText(phone);
        etPhone.setSelection(phone.length());
        etPhone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    boolean bool = NumberJudgeUtils.isMobileNO(etPhone.getText().toString());
                    if (bool == false) {
                        ToastUtil.showToast(mContext, "手机号格式有误，请重新输入");
                        etPhone.setText("");
                    }
                }

            }
        });
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("登录");
        backImageView.setVisibility(View.GONE);
    }

    @Override
    public void initListener() {
        this.btnAuthCode.setOnClickListener(this);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnAuthCode:
                if (vilidInput()) {
                    String phone = etPhone.getText().toString();
                    Intent intent = new Intent(mContext, LoginAuthCodeActivity.class);
                    intent.putExtra(LoginAuthCodeActivity.EXTRA_PHONE, phone);
                    startActivity(intent);
                }
                break;
        }
    }

    public boolean vilidInput() {
        String msg = "";
        if (TextUtils.isEmpty(etPhone.getText())) {
            msg = "手机号不能为空";
        } else if (etPhone.getText().toString().length() != 11) {
            msg = "请输入11位号码";
        } else if (false == NumberJudgeUtils.isMobileNO(etPhone.getText().toString())) {
            msg = "手机号格式有误，请输入正确的手机号";
        }
        if (TextUtils.isEmpty(msg)) {
            return true;
        } else {
            ToastUtil.showToast(this, msg);
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != PermisionUtils.alertDialog)
            PermisionUtils.alertDialog.dismiss();
    }

    public void onEvent(LoginEvent event) {
        if (event != null && event.isSuccess()) {//验证成功，关闭界面
            this.finish();
        }
    }
    public void onEvent(UpgradeEvent event) {
        if (event!=null) {
            if (event.isDownloadComplete()) {
                new UpgradeMgr().checkVersion(LoginActivityV2.this);
            } else if (event.isStartDownload()) {
//                ToastUtil.showToast(this, "开始下载...");
            } else if (event.isNewest()) {
//                ToastUtil.showToast(this, "当前已是最新版本");
            } else if (event.isDownloading()) {
//                ToastUtil.showToast(this, "下载中...");
            }
        }
    }

    private void requestPermission() {
        new RxPermissions(this).requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,Manifest.permission.CAMERA,android.Manifest.permission.RECORD_AUDIO)
                .subscribe(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission.name)) {
                            if (permission.granted) {
                                new UpgradeMgr().checkVersion(LoginActivityV2.this);
                            } else {
                                Log.e(TAG,
                                        "用户拒绝开启存储");
                                PermisionUtils.dialog(LoginActivityV2.this, "读取手机存储");
                            }
                        } else if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permission.name)) {
                            if (permission.granted) {
                                BaiduLocateMgr locateMgr = new BaiduLocateMgr(LoginActivityV2.this, new BaiduLocateMgr.Callback() {
                                    @Override
                                    public void locateSuccess(double lat, double lng, String address) {
                                        MyApp.lat = lat + "";
                                        MyApp.lng = lng + "";
                                    }
                                });
                                locateMgr.startLocate();
                            } else {
                                Log.e(TAG,
                                        "用户拒绝开启定位");
                            }
                        }
                    }
                });
    }

}
